/*
 * Random.h
 *
 *  Created on: 2012/07/10
 *      Author: Weihe
 */

#ifndef RANDOM_H_
#define RANDOM_H_

#include <cstdlib>
#include <cmath>

static float nextFloat()
{
	return (float) rand() / (float) RAND_MAX;
}

static double nextDouble()
{
	return (double) rand() / (double) RAND_MAX;
}

static double nextGaussian()
{
	// See Knuth, ACP, Section 3.4.1 Algorithm C.
	static bool haveNextNextGaussian = false;
	static double nextNextGaussian;
	if (haveNextNextGaussian) {
		haveNextNextGaussian = false;
		return nextNextGaussian;
	} else {
		double v1, v2, s;
		do {
			v1 = 2 * nextDouble() - 1; // between -1 and 1
			v2 = 2 * nextDouble() - 1; // between -1 and 1
			s = v1 * v1 + v2 * v2;
		} while (s >= 1 || s == 0);
		double multiplier = sqrt(-2 * log(s) / s);
		nextNextGaussian = v2 * multiplier;
		haveNextNextGaussian = true;
		return v1 * multiplier;
	}
}
#endif /* RANDOM_H_ */
